package cn.maiyar;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * nacos 实例上下架接口
 * @author wangx
 */
@RestController
@SuppressWarnings(value={"unchecked", "deprecation"})
public class NacosController {

    protected final transient Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    NacosDiscoveryProperties nacosDiscoveryProperties;

    /**
     * 服务注册接口
     * @return
     */
    @GetMapping(value = "/whops/nacos/register")
    public String registerInstance() {
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();

        log.info("register from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port);
        try {
            nacosDiscoveryProperties.namingServiceInstance().registerInstance(serviceName, groupName, ip, port, clusterName);
        } catch (NacosException e) {
            log.error("register from nacos error", e);
            return "error";
        }
        return "success";
    }

    /**
     * 服务注销接口
     * @return
     */
    @GetMapping(value = "/whops/nacos/deregister")
    public String deregisterInstance() {
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();

        log.info("deregister from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port);
        try {
            nacosDiscoveryProperties.namingServiceInstance().deregisterInstance(serviceName, groupName, ip, port, clusterName);
        } catch (NacosException e) {
            log.error("deregister from nacos error", e);
            return "error";
        }
        return "success";
    }
}
